import { Directive, Input } from "@angular/core";
import {
  Validator,
  NG_VALIDATORS,
  AbstractControl,
  ValidationErrors,
  ValidatorFn
} from "@angular/forms";
import { RE } from "../type/re";

export const reValidator = (re: RE): ValidatorFn => (
  control: AbstractControl
): ValidationErrors => {
  let result = false;
  if (re.illegalRule) {
    result = !new RegExp(re.illegalRule).test(control.value || "");
    if (result) {
      result = new RegExp(re.rule).test(String(control.value) || "");
    }
    return result ? {} : { [re.name || "re"]: re.tip };
  } else {
    result = new RegExp(re.rule).test(control.value || "");
    return result ? {} : { [re.name || "re"]: re.tip };
  }
};

@Directive({
  selector: "[nRe]",
  providers: [{ provide: NG_VALIDATORS, useExisting: ReValidator, multi: true }]
})
export class ReValidator implements Validator {
  @Input() reRule: RegExp | string;
  @Input() reName: string;
  @Input() reTip: string;

  validate(control: AbstractControl): ValidationErrors {
    return reValidator({
      rule: this.reRule,
      name: this.reName,
      tip: this.reTip
    })(control);
  }
}
